package com.demo.controls;

import gl.java.utils.FileUtils;
import gl.java.utils.MD5;
import gl.java.utils.StringUtils;

import java.io.File;
import java.util.List;

import com.chanceit.framework.utils.encode.Des;
import com.demo.common.config.DemoConfig;
import com.demo.common.model.User;
import com.demo.interceptor.IMRegInterceptor;
import com.demo.session.TokenManager;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;

public class UserController extends BaseController {

	public static String QQHOST = "openapi.tencentyun.com";
	public static String QQIsLogin = "http://" + QQHOST + "/v3/user/is_login ";

	static {
		if (PropKit.getBoolean("devMode", false)) {
			// QQHOST = "119.147.19.43";
		}
	}

	public void index() {
		renderErr("login please");
		return;
	}

	/**
	 * 登录接口</p> 如果是第三方帐号第一次登录,会注册一个帐号,生成password参数<br>
	 * //thirdid :第三方帐号体系用户唯一识别码 如qq的openID,微信的UID <br>
	 * //thirdtoken:第三方帐号体系用户token,令牌 ,用于调用第三API<br>
	 * //thirdnickname:第三方帐号体系用户昵称 (可选)<br>
	 * //thirdtype:第三方帐号类型 1:qq 2:微信 3:微博 4:...<br>
	 * //注意:第一次登录会注册一个帐号;同一个手机/用户使用不同的第三方帐号登录会生成不同的帐号.<br>
	 */
	public void login() {
		int thirdtype = getParaToInt("thirdtype", 0);
		String username = getPara("username");
		final String thirdToken = getPara("thirdtoken", "");// is QQ openID
		final String thirdID = getPara("thirdid", "");// is QQ access_token
		String password = getPara("password");
		// 看是否是第三方登录
		if (thirdtype > 0 && !isEmpty(thirdToken) && !isEmpty(thirdID)) {
			// 为第三帐号第生成username
			username = genUserNameByThirdAccount(thirdtype, thirdID);
			password = genThridAccountPassword(username, password);
		}
		if (isEmpty(username)) {
			renderErr("username==null");
			return;
		}
		if (isEmpty(password)) {
			renderErr("password==null");
			return;
		}
		List<User> resultList = User.dao.find(
				"select * from user where username = ? ", username);
		if (isEmpty(resultList) || resultList.size() <= 0) {
			// 为第三帐号第一次登录注册帐号
			if (thirdtype > 0) {
				//注册一个用户
				if (regit() == null) {
					return;
				}else{
					resultList = User.dao.find(
							"select * from user where username = ? ", username);	
				}

			} else {
				renderErr("user not regit");
				return;
			}
		} else if (resultList.size() != 1) {
			renderErr("username is repeat");
			return;
		}
		String enCryPassWord = StringUtils.enCryPassWord(resultList.get(0)
				.getId().intValue(), password);
		List<User> resultList2 = User.dao.find(
				"select * from user where username = ? and password = ?",
				username, enCryPassWord);
		if (isEmpty(resultList2) || resultList2.size() <= 0) {
			renderErr("the password is not correct.");
			return;
		} else if (resultList2.size() != 1) {
			renderErr("username and password is repeat");
			return;
		}
		User user = resultList2.get(0);
		user.setPassword("");
		user.setPaypassword("");
		TokenManager.getInstance().add(user.getToken(), user.getId());
		renderJson(user);
	}

	/**
	 * 注册接口,
	 * 
	 * @return
	 */
	public User regit() {
		User user = new User();
		String username = getPara("username");

		int thirdtype = getParaToInt("thirdtype", 0);
		final String thirdToken = getPara("thirdtoken", "");// is QQ openID
		final String thirdID = getPara("thirdid", "");// is QQ access_token
		String password = getPara("password");
		if (thirdtype > 0 && !isEmpty(thirdToken) && !isEmpty(thirdID)) {
			username = genUserNameByThirdAccount(thirdtype, thirdID);
			password = genThridAccountPassword(username, password);
		}
		if (isEmpty(username)) {
			renderErr("username==null");
			return null;
		}

		List<User> resultList = User.dao.find(
				"select * from user where username = ? ", username);
		if (!isEmpty(resultList) && resultList.size() > 0) {
			renderErr("user has exist!");
			return null;
		}

		if (isEmpty(password)) {
			renderErr("password==null");
			return null;
		}

		String nickname = getPara("nickname", "");
		if (isEmpty(nickname)) {
			String thridnickname = getPara("thirdnick", "");
			if (!isEmpty(thridnickname)) {
				nickname = thridnickname;
			} else {
				nickname = username;
			}
		}
		user.set("nickname", nickname);

		String avatar = getPara("avatar");
		String avatarhd = getPara("avatarhd");
		if (isEmpty(avatarhd)) {
			avatarhd = getDefaultAvtor();
		}
		if (isEmpty(avatar)) {
			avatar = avatarhd;
		}
		user.set("avatar", avatar);
		user.set("avatarhd", avatarhd);

		user.setUsername(username);
		user.set("password", password);
		user.set("paypassword", "");
		user.set("tel", getPara("tel", ""));
		user.set("memberpoints", 0);
		user.set("memberpointsbalance", 0);
		user.set("banlance", 0);
		user.set("thirdid", getPara("thirdid", ""));
		user.set("thirdtoken", getPara("thirdtoken", ""));
		user.set("thirdnickname", getPara("thirdnickname", ""));
		user.set("thirdtype", thirdtype);
		user.setImappkey(PropKit.get("HUANXIN_IM_APPKEY", "IM_UNABLE"));
		if (!user.save()) {
			renderErr("user save  fail,maybe sql have some problem!");
			return null;
		}
		user.setImusername(user.getUsername());
		user.setImpassword(MD5.md5(Des.enCrypto(user.getUsername()
				+ user.getId().intValue())));
		user.set("sacncode", genSacnCode(user.getId()));
		user.set("sacncodeimage", genSacnCodeImg(user.getId()));
		user.set("token", StringUtils.genToken(username, user.getId()));
		user.setPassword(StringUtils.enCryPassWord(user.getId(),
				user.getPassword()));

		if (!user.update()) {
			renderErr("user update pw fail,,maybe sql have some problem!");
			user.delete();
			return null;
		}
		user.setPassword("");
		user.setPaypassword("");
		user.setId(0);
		renderJson(user);
		IMRegInterceptor.registIM(user);
		return user;

	}

	private String genThridAccountPassword(String username, String password) {
		password = isEmpty(password) ? username : password;
		return password;
	}

	/**
	 * 根据第三方用户的openID(uid)生成username
	 * 
	 * @param thirdtype
	 *            不允许为空
	 * @param thirdID
	 *            不允许为空
	 * @return
	 */
	private String genUserNameByThirdAccount(int thirdtype, String thirdID) {
		String username;
		switch (thirdtype) {
		case LOGINTYPE_QQ:
			// {"ret":0,"pay_token":"9A7DB00ADF91281EF5AC5E74FD5462E2","pf":"desktop_m_qq-10000144-android-2002-","query_authority_cost":314,"authority_cost":-1358874,"openid":"EA892008072484BF00FC9E92A8C78904","expires_in":7776000,"pfkey":"a876de357cfadfd88eecb768afcdee38","msg":"","access_token":"243DCE9B849F6E9CD954D50895EECD0C","login_cost":164}
			username = "qq_" + thirdID;
			break;
		case LOGINTYPE_WEIXIN:
			username = "wx_" + thirdID;
			break;
		default:
			username = thirdtype + "_" + thirdID;
			break;
		}
		return username;
	}

	/**
	 * 上传头像,并复制到upload文件夹.会从配置文件中读取upload的绝对路径
	 */
	public void uploadavator() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		try {
			UploadFile up = getFile();
			File fileByUpload = up.getFile();
			User user = User.dao.findById(userid);
			if (fileByUpload.exists()) {
				String avatar = File.separator
						+ fileByUpload.getParentFile().getName()
						+ File.separator + fileByUpload.getName();
				try {
					FileUtils.copyFile(fileByUpload, DemoConfig.getFileSavePath()
							+ fileByUpload.getName());	
				} catch (Exception e) {
					e.printStackTrace();
					Log.getLog(getClass()).debug(e.getMessage());
				}
				Log.getLog(getClass()).debug("avatar path:"+avatar);
				user.setAvatar(avatar);
				user.setAvatarhd(avatar);
				if (user.update()) {
					renderJson(user);
				}else{
					renderErr(ERR_DB,"update avator fail");
				}
			} else {
				renderErr("upload fail");
			}
		} catch (Exception e) {
			renderErr(e.getMessage());
			e.printStackTrace();
		}
	}

	// /user/edit?token=df71df92c31111f810a7d89bd2c2e35d&nickname=nickname&avatarhd=sdfsd&password=111111&newpassword=111111&paypassword=111111&newpaypassword=111111
	public void edit() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		boolean isUpdate = false;
		String errmsg = "";
		User user = User.dao.findById(userid);
		String nickname = getPara("nickname", "");
		if (!isEmpty(nickname)) {
			user.setNickname(nickname);
			isUpdate = true;
		}
		String avatarhd = getPara("avatarhd", "");
		if (!isEmpty(avatarhd)) {
			user.setAvatarhd(avatarhd);
			isUpdate = true;
		}
		// login p w
		String newpassword = getPara("newpassword", "");
		if (!isEmpty(newpassword)) {
			String password = getPara("password", "");
			if (!isEmpty(password)) {
				if (checkPassWord(user, password)) {
					user.setPassword(StringUtils.enCryPassWord(user.getId(),
							newpassword));
					user.update();
					isUpdate = true;
				} else {
					errmsg += "passwrod is invalue";
				}
			}
		}
		// pay p w
		String newpaypassword = getPara("newpaypassword", "");
		if (!isEmpty(newpaypassword)) {
			String paypassword = getPara("paypassword", "");
			if (!isEmpty(paypassword)) {
				if (checkPayPassWord(user, paypassword)
						|| isEmpty(user.getPaypassword())) {
					user.setPaypassword(StringUtils.enCryPayPassWord(
							user.getId(), newpaypassword));
					user.update();
					isUpdate = true;
				} else {
					errmsg += " paypasswrod is invalue";
				}
			}
		}
		if (isUpdate) {
			user.update();
			renderErr(errmsg);
		} else {
			renderErr(errmsg);
			return;
		}
	}

	private static boolean checkPassWord(User user, String password) {
		if (StringUtils.enCryPassWord(user.getId(), password).equals(
				user.getPassword())) {
			return true;
		}
		return false;
	}

	private static boolean checkPayPassWord(User user, String password) {
		if (StringUtils.enCryPayPassWord(user.getId(), password).equals(
				user.getPaypassword())) {
			return true;
		}
		return false;
	}

	public static String genSacnCode(int id) {
		return "/scancode";
	}

	public static String genSacnCodeImg(int id) {
		return "/scancode/img";
	}
}